package com.tuanzi.loan.business.service.compensation.impl;

import com.tuanzi.loan.business.repository.compensation.CompensationOrderRepository;
import com.tuanzi.loan.business.service.compensation.CompensationOrderService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.core.vo.PageSearcher;
import com.tuanzi.loan.vo.request.compensation.CompensationOrderRequest;
import com.tuanzi.loan.vo.response.compensation.CompensationOrderResponse;
import com.tuanzi.loan.vo.response.compensation.CompensationOrderTotalResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.retry.RetryException;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author administrator
 * @createTime 2019-06-06 15:39
 */
@Debug
@Service
@Transactional
@Retryable(value = {RetryException.class})
public class CompensationOrderServiceImpl implements CompensationOrderService {
    @Autowired
    private CompensationOrderRepository compensationOrderRepository;
    @Override
    public Page<CompensationOrderResponse> list(PageSearcher<CompensationOrderRequest> pageSearcher) {
        return compensationOrderRepository.list(pageSearcher.getSearchCondition(),pageSearcher.getPageable());
    }

    @Override
    public CompensationOrderTotalResponse total(CompensationOrderRequest request) {
        List<CompensationOrderResponse> list = compensationOrderRepository.totalList(request);
        double totalOrderAmount = list.parallelStream()
                .mapToDouble(e -> Double.parseDouble(e.getAmount())).sum();
        double totalSuccessOrderAmount = list.parallelStream()
                .filter(e -> e.getStatus().equals(12))
                .mapToDouble(e -> Double.parseDouble(e.getAmount())).sum();
        double totalFee = list.parallelStream()
                .filter(e -> e.getStatus().equals(12))
                .mapToDouble(e -> Double.parseDouble(e.getFee())).sum();
        int orderCount = list.size();
        long successOrderCount = list.parallelStream().filter(e -> e.getStatus().equals(12)).count();
        CompensationOrderTotalResponse response = new CompensationOrderTotalResponse();
        response.setTotalOrderAmount(totalOrderAmount);
        response.setTotalSuccessOrderAmount(totalSuccessOrderAmount);
        response.setOrderCount(orderCount);
        response.setSuccessOrderCount((int) successOrderCount);
        response.setTotalFee(totalFee);
        return response;
    }
}
